#coding=utf-8
from __future__ import with_statement

from uliweb import expose, decorators, functions

@decorators.require_login
@expose('/config/user/information')
@expose('/config')
def config_user_info():
#    from uliweb.utils.generic import DetailView
#    from uliweb import orm
#    
#    def boolean_convert(b, obj):
#        if b:
#            return '<div class="ui-icon ui-icon-check"></div>'
#        else:
#            return '<div class="ui-icon ui-icon-closethick"></div>'
#    
#    view = DetailView('user', request.user.id)
#    view.types_convert_map = {orm.BooleanProperty:boolean_convert}
#    return view.run()
    return config_users_view(request.user.id)

@decorators.require_login
@expose('/config/user/edit')
def config_user_edit():
    from uliweb.utils.generic import EditView
    
    view = EditView('user', condition=request.user.id, ok_url=url_for(config_user_info))
    return view.run()
    
@expose('/config/user/change_password')
def config_user_change_password():
    from uliweb.orm import get_model
    
    User = get_model('user')
    user_id = request.GET.get('user_id', None)
    data = {}
    if user_id:
        user = User.get(int(user_id))
        if user:
            data = {'username':user.username}
    from forms import ChangePasswordForm1, ChangePasswordForm2
    if request.user:
        form = ChangePasswordForm1()
    else:
        form = ChangePasswordForm2(data=data)
    if request.method == 'GET':
        return {'form':form, 'ok':False}
    if request.method == 'POST':
        flag = form.validate(request.POST)
        if flag:
            User = get_model('user')
            if user_id:
                user = User.get(User.c.username == form.username.data)
                user.set_password(form.password.data)
                flash('密码保存成功！')
                return redirect('/login?next=/')
            else:
                request.user.set_password(form.password.data)
                flash('密码保存成功！')
                return {'form':form, 'ok':True}
        else:
            if '_' in form.errors:
                message = form.errors['_']
            else:
                message = '存在问题，请修正.'
            flash(message, 'error')
            return {'form':form, 'ok':False}
    
def get_users_list_view(c):
    from uliweb.utils.generic import ListView
    from uliweb.orm import get_model
    from uliweb import request
    from uliweb.core.html import Tag
    from uliweb import orm
    
    def username(value, obj):
        image_url = '<img src="%s" width=20px height=20px align="top"/> ' % functions.get_user_image(obj, size=20)
        return image_url + str(Tag('a', value, href='/config/users/%d' % obj.id))
    
    def boolean_convert(b, obj):
        if b:
            return '<div class="ui-icon ui-icon-check"></div>'
        else:
            return '<div class="ui-icon ui-icon-closethick"></div>'
    
    pageno = int(request.values.get('page', 1)) - 1
    rows_per_page=int(request.values.get('rows', settings.get_var('PARA/FORUM_PAGE_NUMS')))
    
    User = get_model('user')
    query = None
    if request.user.is_manager:
        query = request.user.members.all()
    condition = None
    if c.get('tx'):
        condition = (User.c.tx == int(c['tx'])) & condition
    if c.get('kfzx'):
        condition = (User.c.kfzx == int(c['kfzx'])) & condition
    if c.get('username'):
        condition = (User.c.username.like('%' + c['username'] + '%') | User.c.nickname.like('%' + c['username'] + '%')) & condition
    if c.get('department'):
        condition = (User.c.department == c['department']) & condition
    
    fields_convert_map = {'username':username}
    view =  ListView(User, condition=condition, query=query,
        rows_per_page=rows_per_page, pageno=pageno, 
        fields_convert_map=fields_convert_map, id='users_table')
    view.types_convert_map = {orm.BooleanProperty:boolean_convert}
    return view

@decorators.require_login
@expose('/config/users/list')
def config_users_list():
    from query import create_user_query

    query_view = create_user_query(url_for(config_users_list))
    c = query_view.run()

    view = get_users_list_view(c)
    if 'data' in request.GET:
        return json(view.json())
    else:
        result = view.run(head=True, body=False)
        result.update({'query_form':query_view.form, 'table':view})
        return result
    
@expose('/config/users/data')
def config_users_data():
    result = view.run(head=False, body=True)
    return json(result)

@expose('/config/users/search')
def config_users_search():
    from uliweb.orm import get_model
    
    User = get_model('user')
    username = request.GET.get('term', '')
    if username:
        result = [{'id':obj.id, 'title':obj.username} for obj in User.filter(User.c.username.like('%' + username + '%')).filter(User.c.nickname.like('%' + username + '%'))]
    else:
        result = []
    return json(result)

@decorators.require_login
@expose('/config/users/add')
def config_users_add():
    from uliweb.utils.generic import AddView, ManyToManySelectField
    from uliweb.orm import get_model
    from forms import UserForm, EditUserForm
    import generic.views as g_views
    from functools import partial
    
    get_url = g_views.get_url('/config/users', restful=True)
    
    System = get_model('system')
    
    def pre_save(data):
        if request.user.is_manager:
            data['kfzx'] = request.user._kfzx_
            data['tx'] = request.user._tx_
            data['department'] = request.user.department
    
    def post_save(obj, data):
        obj.set_password(settings.PARA.DEFAULT_PASSWORD)
        obj.users_systems.update(*data['system'])
        obj.observers_systems.update(*data['ob_system'])
        
    if request.user.is_superuser:
        system_field = ManyToManySelectField('system', display_field='name', label='负责系统')
        ob_system_field = ManyToManySelectField('system', display_field='name', label='关注系统')
        fields = ('username', 'nickname', 'department', 'kfzx', 'tx', 'email', 'telphone', 'mobile',
            'is_superuser', 'is_gm', 'is_manager', ('system', system_field), 
            ('ob_system', ob_system_field))
        EditUserForm.user = None
        view = AddView('user', url_for(config_users_list), fields=fields, 
            post_save=post_save, default_data={'manager':request.user.id}, form_cls=EditUserForm)
    elif request.user.is_manager:        
        if request.user.is_gm and request.user.kfzx:
            systems_query = System.filter(System.c.kfzx==request.user._kfzx_)
            ob_systems_query = System.filter(System.c.kfzx==request.user._kfzx_)
            system_field = ManyToManySelectField('system', display_field='name', label='负责系统', query=systems_query)
            ob_system_field = ManyToManySelectField('system', display_field='name', label='关注系统', query=ob_systems_query)
            
            fields = ('username', 'nickname', 'email', 'telphone', 'mobile', 'is_gm','is_manager', 
                ('system', system_field), ('ob_system', ob_system_field))
            
        else:
            systems_query = request.user.users_systems.all()
            ob_systems_query = request.user.observers_systems.all()
            system_field = ManyToManySelectField('system', display_field='name', label='负责系统', query=systems_query)
            ob_system_field = ManyToManySelectField('system', display_field='name', label='关注系统', query=ob_systems_query)
            
            fields = ('username', 'nickname', 'email', 'telphone', 'mobile', 'is_manager', 
                ('system', system_field), ('ob_system', ob_system_field))
            
#        fields = ('username', 'nickname', 'email', 'telphone', 'mobile', 'is_manager', 
#            ('system', system_field), ('ob_system', ob_system_field))
        UserForm.user = None
        view = AddView('user', partial(get_url, 'view'), fields=fields, 
            post_save=post_save, default_data={'manager':request.user.id, 'department':request.user.department},
            pre_save=pre_save, form_cls=UserForm)
    else:
        flash('你不是超级用户或管理员，无法增加用户！')
        return redirect(url_for(config_users_list))
    return view.run()
    
@decorators.require_login
@expose('/config/users/<int:id>')
def config_users_view(id):
    from uliweb.utils.generic import DetailView
    from uliweb import orm
    from config import get_user_image
    import Image
    
    User = orm.get_model('user')
    user = User.get(int(id))
    
    System = orm.get_model('system')
    
    url = get_user_image(user)
    template_data = {'image_url':url}
    
    def boolean_convert(b, obj):
        if b:
            return '<div class="ui-icon ui-icon-check"></div>'
        else:
            return '<div class="ui-icon ui-icon-closethick"></div>'
    
    def system_convert(s, obj):
        from uliweb.core.html import Buf
        
        buf = Buf()
        for x in obj.users_systems.all():
            with buf.li:
                buf.a(x.name, href='/systems/%s' % x.id)
        return str(buf)
    
    def ob_system_convert(s, obj):
        from uliweb.core.html import Buf
        
        buf = Buf()
        for x in obj.observers_systems.all():
            with buf.li:
                buf.a(x.name, href='/systems/%s' % x.id)
        return str(buf)
    
    fields = ['username', 'nickname', 'department', 'kfzx', 'tx', 'email', 'telphone', 'mobile',
        'is_superuser', 'is_gm', 'is_manager', 
        {'name':'system', 'verbose_name':'维护系统'},
        {'name':'ob_system', 'verbose_name':'关注系统'}]
    fields_convert_map = {'system':system_convert, 'ob_system':ob_system_convert}
    view = DetailView('user', int(id), fields=fields, 
        fields_convert_map=fields_convert_map,
        template_data=template_data)
    view.types_convert_map = {orm.BooleanProperty:boolean_convert}
    return view.run()
    
@decorators.require_login
@expose('/config/users/<int:id>/edit')
def config_users_edit(id):
    from uliweb.utils.generic import EditView, ManyToManySelectField
    from uliweb.orm import get_model
    from forms import EditUserForm, UserForm
    
    User = get_model('user')
    System = get_model('system')    #为了实现System与User的ManyToMany的关联
    user = User.get(id)
    
    #if the post_save return True, then it means you've changed the record
    def post_save(obj, data):
        r = user.users_systems.update(*data['system'])
        r1 = user.observers_systems.update(*data['ob_system'])
        return r or r1
    
    if request.user.is_superuser:
        system_field = ManyToManySelectField('system', display_field='name', label='负责系统')
        ob_system_field = ManyToManySelectField('system', display_field='name', label='关注系统')
        fields = ('username', 'department', 'kfzx', 'tx', 'email', 'telphone', 'mobile',
            'is_superuser', 'is_gm', 'is_manager', ('system', system_field),
            ('ob_system', ob_system_field))
        EditUserForm.user = user
        view = EditView('user', condition=int(id), ok_url=url_for(config_users_view, id=id), fields=fields,
            post_save=post_save, data={'system':user.users_systems.ids(), 'ob_system':user.observers_systems.ids()}, form_cls=EditUserForm)
        return view.run()
    elif user.manager.id == request.user.id:
        query = request.user.users_systems.all()
        system_field = ManyToManySelectField('system', display_field='name', label='负责系统', query=query)
        ob_system_field = ManyToManySelectField('system', display_field='name', label='关注系统')
        fields = ('username', 'email', 'telphone', 'mobile', 'is_manager', ('system', system_field),
            ('ob_system', ob_system_field))
        UserForm.user = user
        view = EditView('user', condition=int(id), ok_url=url_for(config_users_view, id=id), fields=fields,
            post_save=post_save, data={'system':user.users_systems.ids(), 
            'ob_system':user.observers_systems.ids()}, form_cls=UserForm)
        return view.run()
    else:
        flash('你不是超级用户或管理员，无法编辑此用户！')
        return redirect(url_for(config_users_list))
    
@decorators.require_login
@expose('/config/users/<int:id>/delete')
def config_users_delete(id):
    from uliweb.utils.generic import DeleteView
    
    if request.user.is_superuser or (request.user.is_manager and request.user.members.has(int(id))):
        view = DeleteView('user', condition=int(id), ok_url=url_for(config_users_list))
        return view.run()
    else:
        flash('你不是超级用户或管理员，无法删除用户！')
        return redirect(url_for(config_users_view, id=int(id)))
    
@decorators.require_login
@expose('/config/users/<int:id>/reset')
def config_users_reset(id):
    from uliweb.orm import get_model
    
    User = get_model('user')
    if request.user.is_superuser:
        user = User.get(int(id))
        user.set_password(settings.PARA.DEFAULT_PASSWORD)
        flash('密码重置成功！')
        return redirect(request.referrer)
    else:
        flash('你不是超级用户无法重置密码！')
        return redirect(url_for(config_users_view, id=int(id)))
        
@decorators.require_login
@expose('/config/users/editimage')
def config_users_edit_image():
    from uliweb.utils.generic import EditView
    from config import _get_portrait_image_filename
    import os
    import Image
    
    def pre_save(obj, data):
        if 'image' in data and data['image']:
            data['image'].filename = _get_portrait_image_filename(request.user.id)
            
    image = _get_portrait_image_filename(request.user.id)
    f = functions.get_filename(image)
    if os.path.exists(f):
        url = functions.get_href(image)
        img = Image.open(f)
        template_data = {'image_url':url, 'size':img.size}
    else:
        url = None
        template_data = {'image_url':url, 'size':(0, 0)}
    
    view = EditView('user', condition=request.user.id, ok_url=url_for(config_users_edit_image),
        pre_save=pre_save, fields=['image'], template_data=template_data)
    
    return view.run()

@decorators.require_login
@expose('/config/users/saveimage')
def config_users_save_image():
    from uliweb.utils.image import crop_resize
    from uliweb.contrib.upload import get_filename
    from config import _get_portrait_image_filename, _get_portrait_image_thumbnail
    
    x = int(request.POST.get('x'))
    y = int(request.POST.get('y'))
    w = int(request.POST.get('w'))
    h = int(request.POST.get('h'))
    
    of = get_filename(_get_portrait_image_filename(request.user.id))
    f = get_filename(_get_portrait_image_thumbnail(request.user.id, size=50))
    crop_resize(of, f, x, y, w, h, size=(50, 50))
    f = get_filename(_get_portrait_image_thumbnail(request.user.id, size=20))
    crop_resize(of, f, x, y, w, h, size=(20, 20))
    flash(_('Save portrait successful'))
    return redirect(url_for(config_users_view, id=request.user.id))

@expose('/config/users/search')
def config_users_search():
    from uliweb.orm import get_model
    
    User = get_model('user')
    
    if request.values.get('term'):
        #如果是超级用户，则全部用户
        condition = None
        if request.user.is_superuser:
            pass
        #如果是条线或测试用户，则使用相同的条线用户
        elif request.user.department in ('1', '3'):
            condition = (User.c.department==request.user.department) & condition
        #如果是开发中心人员，则为相同中心人员
        else:
            condition = (User.c.kfzx==request.user._kfzx_) & condition
        result = []
        name = request.values.get('term')
        for x in User.filter(condition).filter(User.c.username.like('%'+name+'%') | User.c.nickname.like('%'+name+'%')):
            if x.nickname:
                title = x.nickname+'('+x.username+')'
            else:
                title = x.username
            result.append({'id':x.id, 'title':title})
        return json(result)
    else:
        return json([])
            